﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pavilion
{
    internal class PolygonAndPolygonIntersection
    {
        internal PolygonCollisionData CollisionDataA { get; private set; }
        internal PolygonCollisionData CollisionDataB { get; private set; }
        private PolygonPhysicalData APolygonData { get { return CollisionDataA.PhysicalData as PolygonPhysicalData; } }
        private PolygonPhysicalData BPolygonData { get { return CollisionDataB.PhysicalData as PolygonPhysicalData; } }
        private bool checkIntersection;

        public PolygonAndPolygonIntersection(PolygonCollisionData aCollisionData, PolygonCollisionData bCollsionData)
        {
            this.checkIntersection = true;
            this.CollisionDataA = aCollisionData;
            this.CollisionDataB = bCollsionData;

            APolygonData.PhysicalFormChanged += new Action<PhysicalData>(PhysicalData_PhysicalFormChanged);
            BPolygonData.PhysicalFormChanged += new Action<PhysicalData>(PhysicalData_PhysicalFormChanged);
            APolygonData.PositionChanged += new Action<PhysicalData>(PhysicalData_PositionChanged);
            BPolygonData.PositionChanged += new Action<PhysicalData>(PhysicalData_PositionChanged);

            aCollisionData.Disposed += CollisionData_Disposed;
            bCollsionData.Disposed += CollisionData_Disposed;
        }

        internal void UpdateIntersection()
        {
            if (!checkIntersection)
                return;

            checkIntersection = false;

            if (APolygonData.PhysicalBounds.Intersects(BPolygonData.PhysicalBounds))
            {
                CollisionDataA.AddPolygon(BPolygonData);
                CollisionDataB.AddPolygon(APolygonData);
            }
            else
            {
                CollisionDataA.RemovePolygon(BPolygonData);
                CollisionDataB.RemovePolygon(APolygonData);
            }
        }

        private void PhysicalData_PhysicalFormChanged(PhysicalData physicalData) { checkIntersection = true; }

        private void PhysicalData_PositionChanged(PhysicalData physicalData) { checkIntersection = true; }

        private void CollisionData_Disposed()
        {
            if (CollisionDataA == null)
                return;

            CollisionDataA.RemovePolygon(BPolygonData);
            CollisionDataB.RemovePolygon(APolygonData);

            CollisionDataA = null;
            CollisionDataB = null;
        }
    }
}
